import React, { Fragment, Suspense } from "react";
import { Layout } from "antd";
import DocumentTitle from "react-document-title";
import { connect } from "dva";
import { ContainerQuery } from "react-container-query";
import classNames from "classnames";
import Media from "react-media";
import logo from "../assets/logo.png";
import Header from "./Header";
import Context from "./MenuContext";
import SiderMenu from "@/components/SiderMenu";
import getPageTitle from "@/utils/getPageTitle";
import styles from "./BasicLayout.less";
import UserSession from "@/UserSession";
import { getSystemPlatformInfo } from "@/services/platformManagement";
import GlobalFooter from "@/components/GlobalFooter";
// lazy load SettingDrawer
const SettingDrawer = React.lazy(() => import("@/components/SettingDrawer"));

const { Content } = Layout;

const query = {
	"screen-xs": {
		maxWidth: 575,
	},
	"screen-sm": {
		minWidth: 576,
		maxWidth: 767,
	},
	"screen-md": {
		minWidth: 768,
		maxWidth: 991,
	},
	"screen-lg": {
		minWidth: 992,
		maxWidth: 1199,
	},
	"screen-xl": {
		minWidth: 1200,
		maxWidth: 1599,
	},
	"screen-xxl": {
		minWidth: 1600,
	},
};

class BasicLayout extends React.Component {
	componentDidMount() {
		let {
			dispatch,
			route: { routes, path, authority },
			location: { query },
			currentUser,
		} = this.props;
		if (!currentUser.uid) {
			currentUser = JSON.parse(window.localStorage.getItem("currentUser"));
		}
		if (!currentUser) {
			localStorage.clear();
			window.g_app._store.dispatch({
				type: "login/logout",
			});
			return;
		}
		if (query.s) {
			UserSession.setActiveMenu(query.s);
		}

		dispatch({
			type: "user/getCurrent",
			payload: {
				activeSystem: query.s ? query.s : "",
			},
		});
		// dispatch({
		//   type: 'setting/getSetting',
		// });
		// dispatch({
		//   type: 'global/getmenusByUserIds',
		//   payload: { userId: currentUser.uid },
		// });
		dispatch({
			type: "menu/getMenuData",
			payload: { routes, path, authority },
		});

		this.getPlatformInfo()
	}

	getPlatformInfo = async () => {
		const res = await getSystemPlatformInfo();
		console.log(res);
		window.localStorage.setItem("platformInfo", JSON.stringify(res))
	}

	getContext() {
		const { location, breadcrumbNameMap } = this.props;
		return {
			location,
			breadcrumbNameMap,
		};
	}

	getLayoutStyle = () => {
		const { fixSiderbar, isMobile, collapsed, layout,menuData } = this.props;
		if (fixSiderbar && layout !== "topmenu" && !isMobile) {
			return {
				paddingLeft: !menuData || menuData.length === 0 ? '0' : collapsed ? "80px" : "200px",
			};
		}
		return null;
	};

	handleMenuCollapse = (collapsed) => {
		const { dispatch } = this.props;
		dispatch({
			type: "global/changeLayoutCollapsed",
			payload: collapsed,
		});
	};

	renderSettingDrawer = () => {
		// Do not render SettingDrawer in production
		// unless it is deployed in preview.pro.ant.design as demo
		if (process.env.NODE_ENV === "production" && APP_TYPE !== "site") {
			return null;
		}
		return <SettingDrawer />;
	};

	render() {
		const {
			navTheme,
			layout: PropsLayout,
			children,
			location: { pathname },
			isMobile,
			menuData,
			breadcrumbNameMap,
			fixedHeader,
		} = this.props;
		const platformInfo = window.localStorage.getItem("platformInfo")
		const isTop = PropsLayout === "topmenu";
		const contentStyle = !fixedHeader ? { paddingTop: 0 } : {};
		const layout = (
			<Layout>
				{isTop && !isMobile ? null : menuData && menuData.length > 0 ? (
					<SiderMenu
						logo={logo}
						theme={navTheme}
						onCollapse={this.handleMenuCollapse}
						menuData={menuData}
						isMobile={isMobile}
						{...this.props}
					/>
				) : <Layout.Sider width={1} theme="light"></Layout.Sider>}
				<Layout
					style={{
						...this.getLayoutStyle(),
						minHeight: "100vh",
					}}>
					<Header
						menuData={menuData}
						handleMenuCollapse={this.handleMenuCollapse}
						logo={logo}
						isMobile={isMobile}
						{...this.props}
					/>
					<Content className={styles.content} style={contentStyle}>
						{children}
					</Content>
					{
						platformInfo && JSON.parse(platformInfo).bottomInfo ? (
							<GlobalFooter links={[]} copyright={
								<Fragment>
									{JSON.parse(platformInfo).bottomInfo}
								</Fragment>
							} />
						) : ''
					}
				</Layout>
			</Layout>
		);
		return (
			<React.Fragment>
				<DocumentTitle title={getPageTitle(pathname, breadcrumbNameMap)}>
					<ContainerQuery query={query}>
						{(params) => (
							<Context.Provider value={this.getContext()}>
								<div className={classNames(params)}>{layout}</div>
							</Context.Provider>
						)}
					</ContainerQuery>
				</DocumentTitle>
				<Suspense fallback={null}>{this.renderSettingDrawer()}</Suspense>
			</React.Fragment>
		);
	}
}

export default connect(({ global, setting, menu: menuModel, user }) => ({
	collapsed: global.collapsed,
	layout: setting.layout,
	menuData: menuModel.menuData,
	breadcrumbNameMap: menuModel.breadcrumbNameMap,
	currentUser: user.currentUser,
	...setting,
}))((props) => (
	<Media query='(max-width: 599px)'>
		{(isMobile) => <BasicLayout {...props} isMobile={isMobile} />}
	</Media>
));
